package com.lnj.community.service.Impl;


import com.google.code.kaptcha.Producer;
import com.lnj.community.config.JwtConfig;
import com.lnj.community.dao.entity.User;
import com.lnj.community.mapper.UserMapper;
import com.lnj.community.service.RedisTokenService;
import com.lnj.community.service.UserService;
import com.lnj.community.utiles.*;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.awt.image.BufferedImage;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.lnj.community.utiles.CommunityConstant.*;

@Service
@Primary
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;
    private MailClient mailClient; // 注入邮件发送器
    private TemplateEngine templateEngine; // 注入模板引擎 是用来处理模板的 给html页面传值
    private Producer kaptchaProducer; // 注入验证码生成器
    @Value("${server.servlet.context-path}")
    private String contextPath; // 注入项目名称
    @Value("${community.path.domain}")
    private String domain; // 注入域名
    private JwtConfig jwtConfig;
    private RedisTemplate redisTemplate;

    public UserServiceImpl(UserMapper userMapper, MailClient mailClient, TemplateEngine templateEngine,
                           Producer kaptchaProducer ,JwtConfig jwtConfig,RedisTemplate redisTemplate) {
        this.userMapper = userMapper;
        this.mailClient = mailClient;
        this.templateEngine = templateEngine;
        this.kaptchaProducer = kaptchaProducer;
        this.jwtConfig = jwtConfig;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public User findUserById(int id) {
        User user = getCache(id);
        if (user == null) {
            user = initCache(id);
        }
        return user;
    }

    /**
     * 注册用户
     * @param user
     * @return 返回一个map，包含注册结果信息
     *         注册成功：map为空，即注册成功
     *         注册失败：map包含错误信息，即注册失败
     */
    @Override
    public Map<String,Object> register(User user) {
        Map<String,Object> map = new HashMap<>();
        // 空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空");
            return map;
        }
        // 验证账号
        User u = userMapper.selectByName(user.getUsername());
        if (u != null) {
            map.put("usernameMsg", "该账号已存在");
            return map;
        }
        // 验证邮箱
        u = userMapper.selectByEmail(user.getEmail());
        if (u!= null) {
            map.put("emailMsg", "该邮箱已被注册");
            return map;
        }
        // 注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));

        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        // 激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        //http://loclahost:8080/community/activation/用户id/激活码
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);

        return map;
    }

    /**
     * 判断用户是否激活
     * @param userId
     * @param code
     * @return
     */
    @Override
    public int activation(int userId, String code) {
        //根据用户Id获取用户
        User user = userMapper.selectById(userId);
        if (user.getStatus()==1){
            return ACTIVATION_REPEAT;
        }else if (user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId,1);
            removeCache(userId);
            return ACTIVATION_SUCCESS;
        }else {
            return ACTIVATION_FAILURE;
        }
    }

    @Override
    public BufferedImage getKaptcha(HttpServletResponse response) {
        //生成验证码
        String text = kaptchaProducer.createText();
        //生成验证码图片
        BufferedImage image = kaptchaProducer.createImage(text);

        //生成验证码的归属
        String kaptchaOwner = CommunityUtil.generateUUID();
        //存到cookie中
        Cookie cookie = new Cookie("kaptchaOwner",kaptchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        //存到redis中
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(kaptchaKey,text,60, TimeUnit.SECONDS);

        return image;
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param expiredSeconds
     * @return
     */
    @Override
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String,Object> map = new HashMap<>();
        // 空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        // 验证账号
        User user = userMapper.selectByName(username);
        if (user==null){
            map.put("usernameMsg", "该账号不存在");
            return map;
        }
        // 验证状态
        if (user.getStatus()==0){
            map.put("usernameMsg", "该账号未激活");
            return map;
        }
        // 验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)){
            map.put("passwordMsg", "密码不正确");
            return map;
        }

        //生成JWT令牌
        Map<String, Object> claims=new HashMap<>();
        //设置令牌中携带的信息 把用户id放入令牌中
        claims.put(CommunityConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtConfig.getUserSecretKey(), jwtConfig.getUserTtl(), claims);

        //登录成功 把令牌存入redis中
        String redisKey = RedisKeyUtil.getTokenKey(token);
        //键值对 键是token 值是user对象
        redisTemplate.opsForValue().set(redisKey,user,jwtConfig.getUserTtl(), TimeUnit.SECONDS);
        //生成登录凭证
        map.put(LNJ_TOKEN,token);
        //返回用户信息
        map.put("user",user);
        return map;
    }

    /**
     * 退出登录
     * @param token
     */
    @Override
    public void logout(String token) {

    }


    @Override
    public int updateHeadUrl(int userId, String headUrl) {
        int rows = userMapper.updateHeader(userId,headUrl);
        removeCache(userId);
        return rows;
    }

    @Override
    public User findUserByName(String toName) {
        return userMapper.selectByName(toName);
    }

    @Override
    public String findPassword(int id) {
        return userMapper.getPassword(id);
    }

    @Override
    public void updatePassword(int id, String s) {
        userMapper.updatePassword(id,s);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int id) {
        User user = this.findUserById(id);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()){
                    case 0:
                        return AUTHORITY_USER;
                    case 1:
                        return AUTHORITY_ADMIN;
                    case 2:
                        return AUTHORITY_MODERATOR;
                    default:
                        return AUTHORITY_USER;
                }
            }
        });
        return list;
    }

    //1.从redis缓存中获取用户
    private User getCache(int userId){
        String userKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(userKey);
    }
    //2.缓存中没有，从数据库中获取用户
    private User initCache(int userId){
        User user = userMapper.selectById(userId);
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(userKey,user,3600, TimeUnit.SECONDS);
        return user;
    }
    //3.删除缓存中的用户
    private void removeCache(int userId){
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(userKey);
    }

}
